
#include "trace.h"

UINT32 g_logLevel = TRACE_LEVEL_DEFAULT;
UINT32 g_BreakAlways = 0;

#ifdef LOG_TO_QEMU

extern void *mappedSysIoPort;
static long log_lock = 0;

#define write_sysio_ulong(p, v) \
    WRITE_REGISTER_ULONG((PULONG)((char*)mappedSysIoPort + (UINT64)p), v)

void QemuLogPrint(const char *fmt, ...)
{
    char str[QEMU_LOG_MAX_LEN];
    int len, tried = 0;

    if (mappedSysIoPort == NULL) {
        return;
    }

    while (_InterlockedCompareExchange(&log_lock, 1, 0) == 1) {
        if (++tried > 100) {
            return;
        }
    }

    va_list ap;
    va_start(ap, fmt);
    RtlStringCbVPrintfA(str, QEMU_LOG_MAX_LEN, fmt, ap);
    va_end(ap);

    len = strlen(str);
    for (int p = 0; p < len; p += 4) {
        ULONG tmp = 0;
        char* tmpstr = (char*)(&tmp);

        tmpstr[0] = str[p];
        if (p + 1 < len) {
            tmpstr[1] = str[p + 1];
        }
        if (p + 2 < len) {
            tmpstr[2] = str[p + 2];
        }
        if (p + 3 < len) {
            tmpstr[3] = str[p + 3];
        }

        write_sysio_ulong((PULONG)0x3e0, tmp);
    }

    _InterlockedExchange(&log_lock, 0);
}

#endif

void InitQemuLog(void)
{
    g_logLevel = TRACE_LEVEL_DEFAULT;
    g_BreakAlways = 0;
}
